﻿using System;
using Simp.CodeModel;
using Simp.CodeModel.CoreFunctions;

namespace Simp.GraphModel
{
	/// <summary>Encapsulates a 2D-Point in polar coordinates.</summary>
	public class PolarFunction : IFunction
	{
		private static readonly string[] PARAMETER_NAMES = new[] { "r", "theta" };

		#region IFunction Members
		string IFunction.FunctionName
		{
			get { return "Polar"; }
		}

		string[] IFunction.ParameterNames
		{
			get { return PARAMETER_NAMES; }
		}

		IFunctionParameterBinding[] IFunction.DefaultParameterValues
		{
			get { return FunctionHelper.EmptyBindings; }
		}

		IFunction IFunction.Simplify(SimplificationMode simplificationMode, params IFunction[] parameters)
		{
			return null;
		}

		IFunction IFunction.AcceptVisitor(IFunctionVisitor visitor)
		{
			return null;
		}
		#endregion

		/// <summary>Tries to compute the cartesian coordinates of a polar point.</summary>
		/// <param name="r"></param>
		/// <param name="theta"></param>
		/// <param name="x"></param>
		/// <param name="y"></param>
		/// <returns></returns>
		public static bool TryGetCartesian(IFunction r, IFunction theta, out double x, out double y)
		{
			INumericFunction rNumeric = r as INumericFunction;
			INumericFunction thetaNumeric = theta as INumericFunction;

			if (rNumeric == null || thetaNumeric == null)
			{
				x = 0;
				y = 0;

				return false;
			}
			else
			{
				double rValue = rNumeric.GetReal(true).Value;
				double thetaValue = thetaNumeric.GetReal(true).Value;
				double thetaRadianValue = thetaValue * Math.PI / 180;

				if (rValue == 0 && thetaValue == 0)
				{
					x = 0;
					y = 0;

					return true;
				}
				else
				{
					x = rValue * Math.Cos(thetaRadianValue);
					y = rValue * Math.Sin(thetaRadianValue);

					return true;
				}
			}
		}
	}
}